import React, { useMemo, useRef } from "react";
import { Badge } from "antd";

import {ProTable, type TableType, type IProTableRef } from "@yaf/pro-ui";
import { helper } from "@yaf/utils";
import { permission, EnumAuthKey } from "@/service";
import { useThemeToken, getEnv } from "@/constants";

import { getDataAction, getCreateOrEdit, getFilterItems } from './proTableDriver';
import { DataAuthBtn } from './btn';
import { RespDataType } from '../api';

interface ListProps { }

const List: React.FC<ListProps> = () => {
  const { themeToken } = useThemeToken();
  const proTableRef = useRef<IProTableRef>();
  const columns = useMemo(() => getColumns(proTableRef), [proTableRef]);

  return <ProTable
      ref={proTableRef}
      dataAction={getDataAction(proTableRef)}
      rowKey={"id"}
      theme={themeToken.proTableToken}
      headerProps={{
        operatorProps: {
          btnList: [
            { innerType: "create", authKey: EnumAuthKey.sysRole.addButton },
            { innerType: "edit", authKey: EnumAuthKey.sysRole.editButton },
            { innerType: "delete", authKey: EnumAuthKey.sysRole.removeButton }
          ].filter((item) => permission.can(item.authKey)),
          createOrEditProps: {
            modalProps: {
              width: "50%"
            },
            CreateOrEditContent: getCreateOrEdit(),
            getModalTitle: (rowKey) => rowKey ? "编辑角色" : "创建角色",
          },
        },
        filterProps: {
          maxWidth: "50%",
          filterItems: getFilterItems(),
        }
      }}
      contentProps={{
        tableProps: {
          columns,
        }
      }}
      onError={(msg) => console.error(msg)}
    />
}

export default List;

const getColumns = (proTableRef: React.MutableRefObject<IProTableRef>) => {
  const { commonStatusList, roleDataScopeTypeList } = getEnv().globalConfig;
  const statusToInfo = helper.convertArrayToObj(commonStatusList);
  const dataScopeTypeToInfo = helper.convertArrayToObj(roleDataScopeTypeList);

  const columns: TableType.ColumnsType<RespDataType.RoleItem> = [
    {
      title: '角色名称',
      dataIndex: 'name',
    },
    {
      title: '权限范围',
      dataIndex: 'dataScope',
      render: (value) => dataScopeTypeToInfo[value] ? dataScopeTypeToInfo[value].label : "-",
    },
    {
      title: '角色状态',
      dataIndex: 'status',
      render: (value) => {
        const { label, color } = statusToInfo[value];
        return <Badge color={color} text={label}/>
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
    },
    {
      title: "操作",
      render: (_, record) => (<DataAuthBtn roleId={record.id} dataScope={record.dataScope} roleName={record.name} fetchList={proTableRef.current.doFetchList}>数据授权</DataAuthBtn>)
    }
  ];

  return columns;
}
